package com.nmgsr.nettools.net.config;

import com.nmgsr.nettools.net.retrofit.HttpHelper;
import com.nmgsr.nettools.net.retrofit.OkHttpProvider;

import java.util.HashMap;

public class NetManager {

  //  private String baseUrl = "https://mxt.nmgwolf.com/api/v1/";
    private String baseUrl = "http://39.104.200.147:8001/";
    private HashMap<String, String> requestHeader = new HashMap<>();
    private String authorizationToken;

    private NetManager() {
    }

    public static NetManager getInstance() {
        return NetManagerHolder.netManager;
    }

    private static final class NetManagerHolder {
        private static final NetManager netManager = new NetManager();
    }


    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String getBaseImageUrl() {
        return baseUrl.substring(0, baseUrl.length() - 1);
    }

    public HashMap<String, String> getRequestHeader() {
        return requestHeader;
    }

    public void setRequestHeader(HashMap<String, String> requestHeader) {
        this.requestHeader = requestHeader;
    }


    public final void appendHeader(String key, String value) {
        this.requestHeader.put(key, value);
    }

    public final void removeHeader(String key) {
        if (this.requestHeader.containsKey(key)) {
            this.requestHeader.remove(key);
        }
    }

    public void updateHeader() {
        HttpHelper.getInstance().getOkHttpClient().newBuilder().addInterceptor(new OkHttpProvider.HeaderInterceptor()).build();
    }

    /**
     * 设置 Authorization Token
     * @param token JWT Token
     */
    public void setAuthorizationToken(String token) {
        this.authorizationToken = token;
        if (token != null && !token.isEmpty()) {
            appendHeader("Authorization", "Bearer " + token);
        } else {
            removeHeader("Authorization");
        }
        updateHeader();
    }

    /**
     * 清除 Authorization Token
     */
    public void clearAuthorizationToken() {
        this.authorizationToken = null;
        removeHeader("Authorization");
        updateHeader();
    }
}

